package com.clpms.utils.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author caixinyong
 * @date 2023/5/2 12:05 PM
 */

@Aspect
@Component
@Slf4j
public class LoggingAspect {


	@Pointcut("execution(* com.clpms.controller.*.*(..))")
	public void pointcut() {
	}

	@Around("pointcut()")
	public Object logControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();
		Object result = null;
		HttpServletRequest request =
				((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		try {
			result = joinPoint.proceed();
		} finally {
			long endTime = System.currentTimeMillis();
			log.info("接口响应 uri: {}, method:{}, ip: {}, classMethod: {},request: {}, response: {},costTime: {}ms",
					request.getRequestURI(),
					request.getMethod(),
					request.getRemoteAddr(),
					joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
//					JSON.toJSONString(joinPoint.getArgs()),
					JSON.toJSONString(result),
					endTime - startTime);
		}
		return result;
	}

}

